//
//  Page.swift
//  
//
//  Created by tank on 2021/10/9.
//

import Foundation
import UIKit
import RxSwift
import Logging
import LibBase
import LibUI
import LibService

open class Page: PageProtocol {
    var logger = Logger(label: "LibModuleManager.Page")
    
    private let disposeBag = DisposeBag()

    open class var type: String {
        return "page"
    }
    
    public var config: PageConfig
    
    public var id: String?
    
    public var type: String {
        return Self.type
    }
    
    unowned public var module: ModuleProtocol
    
    public var params: [String: Any]?
    
    public var hash: String?
    
    public var completion: ((RouteResult, Any?) -> Void)?
    
    public var popDelta: Int = 1
    
    public var completionParam: Any?
    
    open private(set) var viewController: PageController?
    
    
    required public init(module: ModuleProtocol,
                         id: String?,
                         config: PageConfig?,
                         params: [String : Any]?,
                         hash: String?) {
        
        self.module = module
        self.id = id
        if let config = config {
            self.config = config
            
            guard let params = params else {
                return
            }
            
            config.set(map: params)
        } else {
            self.config = PageConfig.create(map: params)
        }
        self.params = params
        self.hash = hash
        
        logger.logLevel = .debug
        
        if let moduleId = module.id {
            ModuleService.shared
                .pageValue(moduleType: module.type,
                           moduleId: moduleId,
                           pageType: type,
                           pageId: id)
                .subscribe(onSuccess: { [weak self] result in
                    guard let weakSelf = self else {
                        return
                    }
                    
                    guard result.isSuccess() else {
                        weakSelf.logger.info(Logger.Message(stringLiteral: result.message ?? "Request pageValue error!"))
                        return
                    }
                    
                    if let value = result.data {
                        weakSelf.params = Dictionary.merging(value1: value,
                                                             value2: weakSelf.params)
                    }
                })
                .disposed(by: disposeBag)
        }
    }
    
    deinit {
        logger.debug("deinit page type = \(type), id = \(id ?? "nil")")
    }

    open func set(title: String?, subTitle: String?) {
        config.set(title: title, subTitle: subTitle)
    }
    
    open func set(rightMenus: [MenuData]?) {
        config.set(rightMenus: rightMenus)
    }
}
